<template>
  <div class="menu-manage-wrapper">
    <el-form :inline="true" :model="formInline">
      <el-form-item label="资源名称">
        <el-input v-model="formInline.qryWord" placeholder="请输入资源名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchSource">查询</el-button>
        <el-button type="primary" @click="popNewAddDialog">新增资源</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" :height="tableHeight" ref="multipleTable" v-loading="loading" stripe row-key="resourceId" :tree-props="{children:'children'}">
      <el-table-column label="菜单名称" prop="resourceName"></el-table-column>
      <el-table-column label="资源标识" prop="permission"></el-table-column>
      <el-table-column label="资源路径" prop="resourceUrl"></el-table-column>
      <el-table-column label="菜单路径" prop="menuUrl"></el-table-column>
      <el-table-column label="更新时间" prop="updateTime"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.resourceId)">编辑</el-link>&nbsp;
          <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.resourceId)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框 开始 -->
    <el-dialog title="菜单管理" :visible.sync="dialogFormVisible" width="660px" @closed="closeDialog" :close-on-click-modal="false">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog">
        <el-form-item label="父节点" label-width="100px" prop="parentId">
          <el-cascader
            clearable
            v-model="dialogForm.parentId"
            :options="cascaderOpt"
            :props="{ checkStrictly: true, value: 'resourceId' }"
            @change="handleChange"
            placeholder="请选择父节点">
          </el-cascader>
        </el-form-item>
        <el-form-item label="菜单名称" label-width="100px" prop="resourceName">
          <el-input v-model="dialogForm.resourceName" placeholder="请输入菜单名称" autocomplete="off" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="资源标识" label-width="100px" prop="permission">
          <el-input v-model="dialogForm.permission" placeholder="请输入资源标识" autocomplete="off" maxlength="45"></el-input>
        </el-form-item>
        <el-form-item label="资源路径" label-width="100px" prop="resourceUrl">
          <el-input v-model="dialogForm.resourceUrl" placeholder="请输入资源路径" autocomplete="off" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径" label-width="100px" prop="menuUrl">
          <el-input v-model="dialogForm.menuUrl" placeholder="请输入菜单路径" autocomplete="off" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="是否是菜单" label-width="100px" prop="resoyrceType">
          <el-select v-model="dialogForm.resoyrceType" placeholder="请选择是否是菜单">
            <el-option label="是" value="M"></el-option>
            <el-option label="否" value="F"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单排序" label-width="100px" prop="sequence">
          <el-input-number v-model="dialogForm.sequence" controls-position="right" :min="1"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import {
  getResourceList,
  addResource,
  updateResource,
  deleteResource
} from '@/api/systemManage'
import { deepClone } from '@/utils'
export default {
  name: 'MenuManage',
  data () {
    return {
      tableHeight: window.innerHeight - 180,
      formInline: {
        qryWord: ''
      },
      listData: [],
      tableData: [],
      loading: false,
      dialogMode: '',
      dialogFormVisible: false,
      dialogForm: {
        parentId: '',
        resourceName: '',
        permission: '',
        resourceUrl: '',
        menuUrl: '',
        resoyrceType: '',
        sequence: ''
      },
      rules: {
        resourceName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        permission: [{ required: true, message: '请输入资源标识', trigger: 'blur' }],
        resourceUrl: [{ required: true, message: '请输入资源路径', trigger: 'blur' }],
        menuUrl: [{ required: true, message: '请输入菜单路径', trigger: 'blur' }]
      },
      curId: ''
    }
  },
  computed: {
    cascaderOpt () {
      return [
        {
          label: '根节点',
          resourceId: '0'
        },
        ...this.tableData
      ]
    }
  },
  methods: {
    getListDataShow () {
      getResourceList({
        page: 1,
        pageSize: 1000,
        qryWord: this.formInline.qryWord.trim()
      }).then((res) => {
        this.listData = res.data.queryResult
        this.tableData = this.toTree(res.data.queryResult)
      })
    },
    searchSource () {
      this.getListDataShow()
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    handleChange (value) {
      console.log(value)
    },
    editDetail (resourceId) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = resourceId
      this.showToDialog(resourceId)
    },
    deleteDetail (resourceId) {
      this.$confirm('如有子菜单将一并删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteResource({ resourceId }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getListDataShow()
        })
      })
    },
    showToDialog (id) {
      let res = this.listData.filter(item => item.resourceId === id)
      let data = res.length === 0 ? {} : res[0]
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.dialogForm[key] = data[key]
        }
      }
    },
    closeDialog () {
      this.dialogMode = ''
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
    },
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          let requestData = deepClone(this.dialogForm)
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            if (Array.isArray(requestData.parentId)) {
              requestData.parentId = requestData.parentId[requestData.parentId.length - 1]
            }
            addResource(requestData).then((res) => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.getListDataShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.resourceId = this.curId
            if (Array.isArray(requestData.parentId)) {
              requestData.parentId = requestData.parentId[requestData.parentId.length - 1]
            }
            updateResource(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getListDataShow()
              this.dialogFormVisible = false
            })
          }
        } else {
          return false
        }
      })
    },
    toTree (data) {
      // 删除 所有 children,以防止多次调用
      data.forEach((item) => {
        item.label = item.resourceName
        item.value = item.resourceId
        delete item.children
      })
      // 将数据存储为 以 id 为 KEY 的 map 索引数据列
      var map = {}
      data.forEach((item) => {
        map[item.resourceId] = item
      })
      var val = []
      data.forEach((item) => {
        // 以当前遍历项，的pid,去map对象中找到索引的id
        var parent = map[item.parentId]
        // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项新增到，他对应的父级中
        if (parent) {
          (parent.children || (parent.children = [])).push(item)
        } else {
          // 如果没有在map中找到对应的索引ID,那么直接把 当前的item新增到 val结果集中，作为顶级
          val.push(item)
        }
      })
      return val
    }
  },
  mounted () {
    this.getListDataShow()
  }
}
</script>

<style lang="scss" scoped>
.menu-manage-wrapper {
  height: calc(100vh - 180px);
  background-color: #ffffff;
  padding: 15px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  border-radius: 3px;
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-cascader,.el-select {
        width: 100%;
      }
    }
  }
}
</style>
